package cn.campusshop.gateway.filter;

import cn.campusshop.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zhulang
 * @Classname TokenFilter
 * @Description TokenFilter
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();
        //            白名单放行
        if (uri.indexOf("/login") > 0 || uri.indexOf("/sms") > 0 || uri.indexOf("/regist") > 0) {
            return chain.filter(exchange);
        }
        String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        if (!StringUtils.isEmpty(authorization) && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            if ("admin".equals(claims.get("roles")) || "user".equals(claims.get("roles"))) {
                System.out.println("token 验证通过,放行");
//                如果存在请求头丢失情况，请释放下方代码
                ServerHttpRequest build = request.mutate().headers(httpHeaders -> httpHeaders.add(HttpHeaders.AUTHORIZATION, authorization)).build();
                ServerWebExchange webExchange = exchange.mutate().request(build).build();
                return chain.filter(webExchange);
//                认证通过放行
//                return chain.filter(exchange);
            }
        }
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
